package cn.zhb.backend.utils;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/***
 *@Description
 *@Author ZHB
 *@Create 2025/5/11 下午3:38
 **/
@Service
public class LockService {
    private final Map<String, Lock> lockMap = new ConcurrentHashMap<>();

    public boolean tryLock(String key, int timeoutSeconds) {
        Lock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        try {
            return lock.tryLock(timeoutSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void unlock(String key) {
        Lock lock = lockMap.get(key);
        if (lock != null) {
            lock.unlock();
        }
    }
}
